package com.luckberry.murder.controller;

import com.luckberry.murder.entity.User;
import com.luckberry.murder.entity.VIP;
import com.luckberry.murder.service.OrderService;
import com.luckberry.murder.service.VIPService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private OrderService orderService;
    @Resource
    private VIPService vipService;

    @RequestMapping("/account")
    public ModelAndView getAccount(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) return new ModelAndView("redirect:/login");
        ModelAndView modelAndView = new ModelAndView("account");
        modelAndView.getModel().put("user", user);
        VIP vip = vipService.getVIP(user.getUid());
        if (vip != null) {
            long time = vip.getTime().getTime() + (long) vip.getMonth() * 30 * 24 * 60 * 60 * 1000 - new Date().getTime();
            modelAndView.getModel().put("leftDays", time / (24 * 60 * 60 * 1000));
        }
        return modelAndView;
    }

    @RequestMapping(value = "/settings", method = RequestMethod.GET)
    public ModelAndView account(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) return new ModelAndView("redirect:/login");
        ModelAndView modelAndView = new ModelAndView("settings");
        modelAndView.getModel().put("user", user);
        return modelAndView;
    }

    @RequestMapping(value = "/orders", method = RequestMethod.GET)
    public ModelAndView orders(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) return new ModelAndView("redirect:/login");
        ModelAndView modelAndView = new ModelAndView("my_orders");
        modelAndView.getModel().put("user", user);
        modelAndView.getModel().put("orders", orderService.getOrdersByUid(user.getUid()));
        return modelAndView;
    }
}
